from datetime import timedelta

from app.core.BaseResponse import UnicornException
from app.core.random_str import getRandomStr
from app.db.redis import r
from app.model import mysql
from app.service.folder import create_collect_folder
from app.service.jwt_service import create_access_token
from app.settings.config import ACCESS_TOKEN_EXPIRE_MINUTES


async def login(request, user, captcha):
    """
    手机号、验证码快捷登录
    :param request:
    :param user:
    :param captcha:
    :return:
    """
    try:
        redis_user = r.get(f"{user.mobile}:app:captcha").decode()

        if captcha != redis_user:
            raise UnicornException(-1, errmsg="验证码错误")
    except:
        raise UnicornException(-1, errmsg="验证码无效")
    registration_id = request.headers.get("registrationId", "")

    # -------------
    u = await mysql.User.get_or_none(mobile=user.mobile)
    if not u:  # 创建
        nickname = f'新用户{getRandomStr(6)}'
        try:
            u = await mysql.User.create(mobile=user.mobile, nickname=nickname)
        except:
            nickname = f'新用户{getRandomStr(7)}'
            u = await mysql.User.create(mobile=user.mobile, nickname=nickname)
        # 初始化收藏夹
        await create_collect_folder(u.id)
    else:
        await mysql.UserInfo.filter(id=u.id).update(registration_id=registration_id)
    # 绑定推送设备号
    u_info, is_new = await mysql.UserInfo.get_or_create(id=u.id)
    u_info.registration_id = registration_id
    await u_info.save()
    # -------------

    # try:
    #     user = await mysql.User.get(mobile=user.mobile)
    #     await mysql.UserInfo.filter(id=user.id).update(registration_id=registration_id)
    # except:
    #     try:
    #         user = await mysql.User.create(mobile=user.mobile, nickname="新用户%s" % getRandomStr(6))
    #     except:
    #         user = await mysql.User.create(mobile=user.mobile, nickname="新用户%s" % getRandomStr(7))
    #     await mysql.UserInfo.create(registration_id=registration_id)
    #     # 初始化收藏夹
    #     await create_collect_folder(user.id)

    access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = create_access_token(data={"sub": u.mobile},
                                       expires_delta=access_token_expires)
    user_is_invite = await mysql.UserInfo.get(id=u.id)
    res = {"token": "bearer" + " " + str(access_token.decode()), "step": user_is_invite.step}
    return res


async def user_logout(user_id):
    """
    退出
    :param user_id:
    :return:
    """
    # 清除设备号
    await mysql.UserInfo.filter(id=user_id).update(registration_id='')


async def invitation_code(code, current_user):
    """
    绑定邀请码
    :param code:
    :param current_user:
    :return:
    """
    if str(code.code) != "9999":
        raise UnicornException(-1, errmsg="邀请码错误")

    await mysql.UserInfo.filter(id=current_user.id).update(step=2)

    return


async def login_debug(mobile):
    access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)

    access_token = create_access_token(data={"sub": mobile},
                                       expires_delta=access_token_expires)

    return access_token
